#pragma once
#include <vector>
#include <fstream>
#include <sstream>
#include <Windows.h>
#include <locale>
#include <codecvt>
#include <filesystem>
#include <QImage>
#include <QFileInfo>
#include <QDir>


class PngWriter {
public:
    PngWriter() : width_(0), height_(0), current_row_(0), saved_(false) {}

    ~PngWriter() {
        // 如果还没保存并且已经初始化了图像，尝试保存
        if (!saved_ && !image_.isNull()) {
            std::string errorMsg;
            try {
                finalize(errorMsg);
            } catch (...) {
                // 在析构函数中不抛出异常
            }
        }
    }

    bool init(const std::string& filename, int width, int height, std::string& errorMsg);

    void writeRows(unsigned char** rows, int num_rows);

    int currentRow() { return current_row_; }

    int totalRows() { return height_; }

    // 新增方法用于保存文件
    bool finalize(std::string& errorMsg, std::function<void(int)> progressCallback = nullptr);

private:
    int width_;
    int height_;
    int current_row_;
    QImage image_;
    QString filename_;
    bool saved_;  // 标记文件是否已保存
};
